有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在给出正确答案之前,是否要求回答?Java Eclipse

我基本上是在玩eclipse,以保留我在Java入门课程中学到的东西。我即将注册高级编程,我有一个初学者的问题

我在下面创建了这个小程序,因为我很难理解这些方法。现在我有了一般的概念,我有一个新的问题。我在下面有一个do-while语句,如果您输入简单加法问题的正确答案,它就会起作用。如果您输入了错误的答案,它将要求您再次尝试该问题(如我所愿)。如果您再次输入错误答案,程序将停止。我希望它能提示用户输入答案,直到答案正确为止。我该怎么做

import java.util.Scanner; //needed for input

public class PracticeMethod {
    public static void main(String[] args) {
        // Create a Scanner

        System.out.println(");
        System.out.println();
        makesPerfect();
        String anotherRun = "yes";

        Scanner input = new Scanner(System.in);

    }

    static void makesPerfect() {
        Scanner input = new Scanner(System.in);
        String anotherRun;
        do {

            System.out.print(" Math");
            int x = (int) (Math.random() * 10) + 1;
            int y = (int) (Math.random() * 10) + 1;

            System.out.print(" What is " + x + "+" + y + "? ");
            double answer = 0.0;
            answer = input.nextDouble();
            if (answer == x + y) {
                System.out.println(" Yes, you are correct.");

            }
            if (answer != x + y) {
                System.out.print(" No, that is not correct. ");
                System.out.println();
                System.out.print(" Why dont you try again? ");
                System.out.println();
                System.out.println();
                System.out.print(" What is " + x + "+" + y + "? ");
                answer = input.nextDouble();
            }
            System.out.println();

            System.out.print("Enter yes if you want to run again: ");
            anotherRun = input.next();
            input.nextLine(); // causes skipping issue to fix
            System.out.print("\n\n\n");
        } while (anotherRun.equalsIgnoreCase("yes"));
    }
}

共 (1) 个答案

  1. # 1 楼答案

    if语句检查答案是否正确。这样你就会一直问正确答案,直到你得到它

    while(answer != x + y) {
        System.out.print(" No, that is not correct. ");
        System.out.println();
        System.out.print(" Why dont you try again? ");
        System.out.println();
        System.out.println();
        System.out.print(" What is " + x + "+" + y + "? ");
        answer = input.nextDouble();
    }
    

    也为正确使用StackOverflow和努力学习而感到自豪!也许有一天你会为我回答问题